import React, { createContext, ReactElement } from 'react';
import { State, Action, Context, Tab } from './types';
import actions from './actions';
import Provider from '../../components/Provider';
import { TABS } from './constant';

export const initialState: State = {
  currentTab: TABS[0],
  tabs: TABS
};

export const reducer = (state: State, action: Action): State => {
  switch (action.type) {
    case 'SET_CURRENT_TAB': {
      let { tabs } = state;
      tabs = tabs.map(
        (item): Tab => {
          if (item.id === action.value.id) {
            return { ...action.value, hasShow: true };
          }
          return item;
        }
      );
      return { ...state, currentTab: action.value, tabs };
    }
    case 'SET_TABS': {
      return { ...state, tabs: action.value, currentTab: action.value[0] };
    }
    default:
      return state;
  }
};

export const Store = createContext<Context>({
  state: initialState
});

export default (props: { [key: string]: any }): ReactElement => {
  return (
    <Provider
      reducer={reducer}
      initialState={initialState}
      Store={Store}
      actions={actions}
      {...props}
    />
  );
};
